﻿using Newtonsoft.Json;
using PlutoStudio.Net.Messages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public static class JsonExtensions
{
    public static string Serialize(this object item)
    {
        var setting = new Newtonsoft.Json.JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() };
        return JsonConvert.SerializeObject(item, setting);
    }

    public static T Deserialize<T>(this string value)
    {
        return JsonConvert.DeserializeObject<T>(value);
    }
}
public static class MessageExtensions
{
    public static Message SetData(this Message message, byte[] data)
    {
        message.Length = data.Length;
        message.Data = data;
        return message;
    }

    public static Message SetData(this Message message, object data)
    {
        var content = data.Serialize();
        return SetData(message, content);
    }

    public static Message SetData(this Message message, string data)
    {
        var buffer = System.Text.Encoding.UTF8.GetBytes(data);
        return SetData(message, buffer);
    }


    public static Message SetData(this Message message, byte data)
    {
        message.Length = 1;
        message.Data = new byte[] { data };
        return message;
    }

    public static Message SetData(this Message message, int data)
    {
        byte[] buffer = new byte[4];
        buffer[0] = (byte)data;
        buffer[1] = (byte)(data >> 0x8);
        buffer[2] = (byte)(data >> 0x10);
        buffer[3] = (byte)(data >> 0x18);
        return SetData(message, buffer);
    }

    public static string GetContentString(this Message message)
    {
        return Encoding.UTF8.GetString(message.Data);
    }

    public static T GetContentObject<T>(this Message message)
    {
        var content = GetContentString(message);
        if (string.IsNullOrWhiteSpace(content))
        {
            return default(T);
        }
        return content.Deserialize<T>();
    }
}
